package com.hrp.analyzer.spider.pipline;

import com.hrp.analyzer.model.Chapter;
import com.hrp.analyzer.spider.helper.SpiderHelper;
import com.hrp.analyzer.util.FileUtils;
import com.hrp.analyzer.util.StringUtils;
import com.hrp.analyzer.util.compat.PrintLog;

import java.io.File;
import java.io.IOException;

/**
 * 保存为文本文件的pipeline
 * 路径为当前目录的下的downloads
 *
 * @author hrp
 * @date 2020/12/23 10:58 下午
 */

public class TxtPipeline extends AbstractTextPipeline {
    private static final String DOWNLOAD_FILE_FORMAT = "%s/%d.%s.txt";
    /**
     * 是否合并文件
     */
    private boolean merge;
    /**
     * 删除章节文件
     */
    private boolean deleteVolume;

    public TxtPipeline setMerge(boolean merge) {
        this.merge = merge;
        return this;
    }

    public TxtPipeline setDeleteVolume(boolean deleteVolume) {
        this.deleteVolume = deleteVolume;
        return this;
    }

    @Override
    public void processChapter(Chapter chapter) {
        String filePath = String.format(DOWNLOAD_FILE_FORMAT, getFilePath(), chapter.getOrder(), StringUtils.removeInvalidSymbol(chapter.getName()));
        try {
            // 写入文件
            FileUtils.writeString(filePath, chapter.getContent(), getCharset());
        } catch (IOException e) {
            PrintLog.log.error("保存章节内容到：{} 失败.", filePath, e);
        }
    }

    @Override
    public void onComplete() {
        if (merge) {
            try {
                SpiderHelper.mergeNovel(new File(getFilePath()), getNovel().getTitle().concat(".txt"), deleteVolume);
            } catch (Exception e) {
                PrintLog.log.error("文件合并失败：{}", getFilePath(), e);
            }
        }
    }
}
